#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 rambla.eu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.import os
import platform, os, sys, datetime
import unittest
import setup_environ
import json
import raws_json
from raws_json.raws_service import RawsService, Feed, Query
from raws_json.meta.service import MetaService
from raws_json.rass.service import RassService
from raws_json.meta.meta import *

class LangTest(unittest.TestCase):
    """ Some simple searches """

    @classmethod
    def setUpClass(cls):
        cls.meta_service = MetaService(username = setup_environ.TEST_USERNAME, password = setup_environ.TEST_PASSWORD, server = setup_environ.TEST_SERVER)
        cls.rass_service = RassService(username = setup_environ.TEST_USERNAME, password = setup_environ.TEST_PASSWORD, server = setup_environ.TEST_RASS_SERVER)
        # delete all existing content instances
        feed = cls.meta_service.getContentList()
        mf = Feed(feed)
        for e in mf.entries:
            cls.meta_service.deleteContent(e)
        # make sure files exist on the CDN
        status = cls.rass_service.getItemHeaderFromPath("aaa.mp4")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "aaa.mp4", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("aaa.webm")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "aaa.webm", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("aaa_00.jpg")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "aaa_00.jpg", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("aaa_50.jpg")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "aaa_50.jpg", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("aaa_100.jpg")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "aaa_100.jpg", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("bbb.mp4")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "bbb.mp4", local_path = setup_environ.LOCAL_FILE)
        status = cls.rass_service.getItemHeaderFromPath("ccc.mp4")
        if status != 200:
            cls.rass_service.postItem(dirpath = "", filename = "ccc.mp4", local_path = setup_environ.LOCAL_FILE)
            
        # Cars -> multi-language (en,nl,fr)
        af1 = FileObj(path = "aaa.mp4", media_type = "video", duration = 60)
        af2 = FileObj(path = "aaa.webm", media_type = "video", duration = 60)
        af3 = FileObj(path = "aaa_00.jpg", media_type = "image")
        af4 = FileObj(path = "aaa_50.jpg", media_type = "image")
        af5 = FileObj(path = "aaa_100.jpg", media_type = "image")
        cls.am1e = MetaObj(meta_name = "Title", vocab = "dc", text = u"Cars", lang = "en")
        cls.am1n = MetaObj(meta_name = "Title", vocab = "dc", text = u"Autos", lang = "nl")
        cls.am1f = MetaObj(meta_name = "Title", vocab = "dc", text = u"Voitures", lang = "fr")
        cls.am2 = MetaObj(meta_name = "Creator", vocab = "dc", text = u"Pixar")
        cls.am3 = MetaObj(meta_name = "Publisher", vocab = "dc", text = u"Disney")
        cls.am4e = MetaObj(meta_name = "Description", vocab = "dc", text = u"Cars is a 2006 American computer-animated comedy-adventure film produced by Pixar", lang = "en")
        cls.am4n = MetaObj(meta_name = "Description", vocab = "dc", text = u"Cars is een Amerikaanse computeranimatiefilm uit 2006, onder regie van John Lasseter en Joe Ranft. Het is de zevende van de Pixar-films, en de laatste film van Pixar voordat deze door Disney gekocht werd.", lang = "nl")
        cls.am4f = MetaObj(meta_name = "Description", vocab = "dc", text = u"Cars : Quatre Roues ou Les Bagnoles au Québec est le septième long-métrage d'animation entièrement en images de synthèse des studios Pixar. Sorti en 2006 aux États-Unis et co-produit par les studios Disney, le film se déroule dans un monde peuplé de voitures anthropomorphes.", lang = "fr")
        cls.cars_mc = MetaContent(name = "cars", tags = ["cars", "animated", "movie", "Pixar"], file_objs = [af1,af2,af3,af4,af5], meta_objs = [cls.am1e,cls.am1f,cls.am1n,cls.am2,cls.am3,cls.am4e,cls.am4n,cls.am4f])
        cars_entry = cls.meta_service.createContent(cls.cars_mc.to_entry())

        # Big Buck Bunny -> english + dutch
        bf1 = FileObj(path = "bbb.mp4", media_type = "video", duration = 120)
        cls.bm1e = MetaObj(meta_name = "Title", vocab = "dc", text = u"Big Buck Bunny", lang = "en")
        cls.bm1n = MetaObj(meta_name = "Title", vocab = "dc", text = u"Reuze Stoere Konijn", lang = "nl")
        cls.bm2 = MetaObj(meta_name = "Creator", vocab = "dc", text = u"Blender institute", lang = "en")
        cls.bm3e = MetaObj(meta_name = "Description", vocab = "dc", text = u"Big Buck Bunny (code-named Peach) is a short computer animated film by the Blender Institute", lang = "en")
        cls.bm3n = MetaObj(meta_name = "Description", vocab = "dc", text = u"Big Buck Bunny (codenaam: Peach) is een animatiefilm gemaakt door het Blender Institute met behulp van opensourcesoftware, net zoals het voorgaande project Elephants Dream (2006).", lang = "nl")
        cls.bm4 = MetaObj(meta_name = "Audience", vocab = "dc", text = "6+")
        cls.big_buck_bunny_mc = MetaContent(name = "big_buck_bunny", tags = ["animated", "movie", "Blender", "python", "BigBuckBunny"], file_objs = [bf1,], meta_objs = [cls.bm1e, cls.bm1n, cls.bm2,cls.bm3e,cls.bm3n,cls.bm4])
        big_buck_bunny_entry = cls.meta_service.createContent(cls.big_buck_bunny_mc.to_entry())

        # Cars trailer -> no language elements
        cf1 = FileObj(path = "ccc.mp4", media_type = "video", duration = 30)
        cm1 = MetaObj(meta_name = "Title", vocab = "dc", text = "Cars Trailer")
        cm2 = MetaObj(meta_name = "Creator", vocab = "dc", text = "Pixar")
        am2 = MetaObj(meta_name = "Publisher", vocab = "dc", text = "Pixar")
        cm3 = MetaObj(meta_name = "Description", vocab = "dc", text = "Trailer of the Cars movie")
        cls.cars_trailer_mc = MetaContent(name = "cars_trailer", tags = ["animated", "cars", "trailer"], file_objs = [cf1,], meta_objs = [cm1, cm2, cm3])
        cars_trailer_entry = cls.meta_service.createContent(cls.cars_trailer_mc.to_entry())
            
    def test_get_entry_single_lang(self):
        """ Do a get content entry request with 'lang=nl' : cars?lang=nl """
        # query is possible on value
        qry = Query()
        qry["lang"] = "nl"
        e = self.meta_service.getContentInstance(name = "cars", query = qry)
        mc = MetaContent(entry = e)
        if unicode(mc.name) == unicode(self.cars_mc.name):
            self.assertNotEqual(mc, self.cars_mc)
            self.assertTrue(mc.compare_meta_objs([self.am1n,self.am2,self.am3,self.am4n]))
        else:
            self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)

    def test_get_feed_single_lang(self):
        """ Do a get feed request with 'lang=nl' """
        qry = Query()
        qry["lang"] = "nl"
        feed = self.meta_service.getContentList(query = qry)
        mf = Feed(feed)
        self.assertEqual(3, len(mf.entries))
        for e in mf.entries:
            mc = MetaContent(entry = e)
            if unicode(mc.name) == unicode(self.cars_mc.name):
                self.assertNotEqual(self.cars_mc, mc)
                self.assertTrue(mc.compare_meta_objs([self.am1n,self.am2,self.am3,self.am4n]))
            elif unicode(mc.name) == unicode(self.big_buck_bunny_mc.name):
                self.assertNotEqual(self.big_buck_bunny_mc, mc)
                self.assertTrue(mc.compare_meta_objs([self.bm1n,self.bm3n,self.bm4]))
            elif unicode(mc.name) == unicode(self.cars_trailer_mc.name):
                self.assertEqual(self.cars_trailer_mc, mc)
            else:
                self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)
        
    def test_get_all_lang_feed__search_meta(self):
        """ Get all languages doing a meta search: meta=dc:Title:Autos """
        # query is possible on value
        qry = Query()
        qry["meta"] = "dc:Title:Autos"
        feed = self.meta_service.getContentList(query = qry)
        mf = Feed(feed)
        self.assertEqual(1, len(mf.entries))
        for e in mf.entries:
            mc = MetaContent(entry = e)
            if unicode(mc.name) == unicode(self.cars_mc.name):
                self.assertEqual(self.cars_mc, mc)
            else:
                self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)

    def test_get_single_lang_feed__search_meta(self):
        """ Get a single language doing a meta search: meta=dc:Title:Autos;lang=nl """
        # query is possible on value
        qry = Query()
        qry["meta"] = "dc:Title:Autos"
        qry["lang"] = "nl"
        feed = self.meta_service.getContentList(query = qry)
        mf = Feed(feed)
        self.assertEqual(1, len(mf.entries))
        for e in mf.entries:
            mc = MetaContent(entry = e)
            if unicode(mc.name) == unicode(self.cars_mc.name):
                self.assertNotEqual(self.cars_mc, mc)
                self.assertTrue(mc.compare_meta_objs([self.am1n,self.am2,self.am3,self.am4n]))
            else:
                self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)

    def test_get_double_lang_feed__search_meta(self):
        """ Get two out of three languages doing a meta search: meta=dc:Title:Autos;lang=nl """
        # query is possible on value
        qry = Query()
        qry["meta"] = "dc:Title:Autos"
        qry["lang"] = "nl,fr"
        feed = self.meta_service.getContentList(query = qry)
        mf = Feed(feed)
        self.assertEqual(1, len(mf.entries))
        for e in mf.entries:
            mc = MetaContent(entry = e)
            if unicode(mc.name) == unicode(self.cars_mc.name):
                self.assertNotEqual(mc, self.cars_mc)
                self.assertTrue(mc.compare_meta_objs([self.am1n,self.am1f,self.am2,self.am3,self.am4n,self.am4f]))
            else:
                self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)

    def test_get_single_lang_feed_multiple_entries__search_meta(self):
        """ Get a single language doing a meta search which returns multiple entries: iqmeta=dc:Title:Autos;lang=nl """
        # query is possible on value
        qry = Query()
        qry["iqmeta"] = "animatie"
        qry["lang"] = "nl"
        feed = self.meta_service.getContentList(query = qry)
        mf = Feed(feed)
        self.assertEqual(2, len(mf.entries))
        for e in mf.entries:
            mc = MetaContent(entry = e)
            if unicode(mc.name) == unicode(self.cars_mc.name):
                self.assertNotEqual(mc, self.cars_mc)
                self.assertTrue(mc.compare_meta_objs([self.am1n,self.am2,self.am3,self.am4n]))
            if unicode(mc.name) == unicode(self.big_buck_bunny_mc.name):
                self.assertNotEqual(mc, self.big_buck_bunny_mc)
                self.assertTrue(mc.compare_meta_objs([self.bm1n,self.bm3n,self.bm4]))
            else:
                self.assertTrue("test_search_meta(): unexpected entry name" + mc.name)
                

def suite():
   suite = unittest.TestSuite()
   suite.addTest(unittest.makeSuite(LangTest))
   return suite

if __name__=='__main__':
    unittest.main()
